package com.nisco.dms.service;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.nisco.dms.entity.User;
import com.nisco.dms.exception.ExistedException;
import com.nisco.dms.exception.ServiceException;
import com.nisco.dms.repository.UserDao;
import com.nisco.dms.shiro.ShiroDbRealm;
import com.nisco.dms.shiro.ShiroDbRealm.HashPassword;
import com.nisco.dms.util.dwz.Page;
import com.nisco.dms.util.dwz.PageUtils;

/**
 * 
 * @author joey
 * 
 */
// Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional(readOnly = true)
public class UserService extends BaseService<User, String> {

	private static final Logger logger = LoggerFactory.getLogger(UserService.class);
	@Autowired
	private UserDao userDao;
	@Autowired
	private ShiroDbRealm shiroRealm;

	public UserService() {

	}

	/**
	 * 构造函数
	 * 
	 * @param jpaRepository
	 */
	@Autowired
	public UserService(UserDao userDao) {
		super((JpaRepository<User, String>) userDao);
		this.userDao = userDao;
	}

	@Transactional
	public void save(User user) throws ExistedException {
		if (userDao.findBystrAccount(user.getStrAccount()) != null) {
			throw new ExistedException("用户添加失败，登录名：" + user.getStrAccount() + "已存在。");
		}

		/*if (userDao.findByStrName(user.getStrName()) != null) {
			throw new ExistedException("用户添加失败，真实名：" + user.getStrName() + "已存在。");
		}*/

		// 设定安全的密码，使用passwordService提供的salt并经过1024次 sha-1 hash
		if (StringUtils.isNotBlank(user.getPlainPassword()) && shiroRealm != null) {
			HashPassword hashPassword = shiroRealm.encrypt(user.getPlainPassword());
			user.setStrSalt(hashPassword.salt);
			user.setStrPassword(hashPassword.password);
		}

		userDao.save(user);
		shiroRealm.clearCachedAuthorizationInfo(user.getStrAccount());
	}

	@Transactional
	public void update(User user) {
		// if (isSupervisor(user.getId())) {
		// logger.warn("操作员{},尝试修改超级管理员用户",
		// SecurityUtils.getSubject().getPrincipal());
		// throw new ServiceException("不能修改超级管理员用户");
		// }
		// 设定安全的密码，使用passwordService提供的salt并经过1024次 sha-1 hash

		if (StringUtils.isNotBlank(user.getPlainPassword()) && shiroRealm != null) {
			HashPassword hashPassword = shiroRealm.encrypt(user.getPlainPassword());
			user.setStrSalt(hashPassword.salt);
			user.setStrPassword(hashPassword.password);
		}

		userDao.save(user);
		shiroRealm.clearCachedAuthorizationInfo(user.getStrAccount());
	}

	@Transactional
	public void delete(String id) throws ServiceException {
		if (isSupervisor(id)) {
			logger.warn("操作员{}，尝试删除超级管理员用户", SecurityUtils.getSubject().getPrincipal() + "。");
			throw new ServiceException("不能删除超级管理员用户。");
		}
		userDao.delete(id);
	}

	public User get(String userName) {
		return userDao.findBystrAccount(userName);
	}
	public User findById(String id) {
		return userDao.findById(id);
	}
	public List<User> find(Page page, String name) {
		org.springframework.data.domain.Page<User> pageUser = userDao.findByStrAccountContaining(name, PageUtils.createPageable(page));
		PageUtils.injectPageProperties(page, pageUser);
		return pageUser.getContent();
	}
	
	public List<User> findByCompanyAndIsActivite(Page page, String CompanyId,int isActivite) {
		org.springframework.data.domain.Page<User> pageUser = userDao.findByCompanyIdAndIntIsActive(CompanyId, isActivite, PageUtils.createPageable(page));
		PageUtils.injectPageProperties(page, pageUser);
		return pageUser.getContent();
	}
	/**
	 * 判断是否超级管理员.
	 */
	private boolean isSupervisor(String id) {
		return id == "1";
	}
}
